//检查版本

import { GetVersion } from "./api.js"

const versionUtil = {
    //获取服务器的版本号
    getAppVersionForServer(appId) {
        return new Promise((resolve, reject) => {
            //#ifdef APP
            //当前app包名
            //请求接口固定为
            let updateUrl = "https://shop.yunlianshang.net/AppApi/Update/GetVersion?applicationId=" + appId
            GetVersion(updateUrl).then((res) => {
                if (res) {
                    //服务器版本号
                    let serverV = res.data.versionCode
                    //app当前版本号
                    // let currentV = plus.runtime.versionCode
                    let currentV;
                    //对比版本
					plus.runtime.getProperty(plus.runtime.appid, (info) => {
						console.log(JSON.stringify(info));
						currentV = info.versionCode;
						let hasNew = serverV > currentV
						res.hasNew = hasNew
						console.log(serverV)
						console.log(currentV)
						resolve(res)
					}) 
                   
                }
            })
            //#endif
        })
    },
    //下载并安装
    downApp(url, progressBack) {
        let dTask = plus.downloader.createDownload(url, {}, (d, status) => {
            if (status == 200) {
                var fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename)
                plus.runtime.install(
                    fileSaveUrl,
                    {
                        force: true,
                    },
                    () => {},
                    (e) => {
                        console.log("failed: " + e.message)
                    },
                )
            } else {
                plus.nativeUI.alert("请联网后重试")
            }
            plus.nativeUI.closeWaiting()
        })
        // 监听下载进度
        dTask.addEventListener("statechanged", function (task, status) {
            if (!dTask) {
                return
            }
            switch (task.state) {
                case 1:
                    console.log("开始下载...")
                    break
                case 2:
                    console.log("正在下载...")
                    break
                case 3: // 已接收到数据
                    var progressVal = (task.downloadedSize / task.totalSize) * 100
                    if (progressBack) {
                        progressBack(Number(progressVal))
                    }
                    break
                case 4:
                    dTask = null
                    console.log("正在打开文件...")
                    break
            }
        })
        // 开始下载
        dTask.start()
    },
}

module.exports = {
    getAppVersionForServer: versionUtil.getAppVersionForServer,
    downApp: versionUtil.downApp,
}
